package com.goldze.mvvmhabit.ui.chat;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.goldze.mvvmhabit.BR;
import com.goldze.mvvmhabit.R;
import com.goldze.mvvmhabit.app.AppViewModelFactory;
import com.goldze.mvvmhabit.databinding.ActivityChatContentListBinding;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.FileUtil;
import me.goldze.mvvmhabit.utils.MaterialDialogUtils;

/**
 * 一个MVVM模式的登陆界面
 */
public class ChatContentListActivity extends BaseActivity<ActivityChatContentListBinding, ChatContentListViewModel> {

    private final int CAMERA_RESULT_CODE = 0;
    private final int SELECTPIC_RESULT_CODE = 1;
    private File filePath = null;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_chat_content_list;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public ChatContentListViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(ChatContentListViewModel.class);
    }

    @Override
    public void initViewObservable() {
        viewModel.rollingBottom.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer index) {
                binding.chatContentList.scrollToPosition(index - 1);
            }
        });
        //注册监听相机权限的请求
        viewModel.requestCameraPermissions.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                requestCameraPermissions();
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        String path = getFilesDir() + File.separator + "images" + File.separator;
        filePath = new File(path, "photo.jpg");
        //初始化标题
        viewModel.initToolbar();
        viewModel.timedTransmission();
    }

    /**
     * 请求相机权限
     */
    private void requestCameraPermissions() {
        //请求打开相机权限
        RxPermissions rxPermissions = new RxPermissions(ChatContentListActivity.this);
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            showSelectDialog();
                        }
                    }
                });
    }

    public void showSelectDialog() {
        List<String> list = new ArrayList<>();
        list.add("拍照");
        list.add("相册");
        MaterialDialogUtils.showBasicListDialog(ChatContentListActivity.this, "请选择", list, new MaterialDialog.ListCallback() {
            @Override
            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                if (position == 0) {
                    takePhoto();
                } else {
                    Intent albumIntent = new Intent(Intent.ACTION_PICK);
                    albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(albumIntent, SELECTPIC_RESULT_CODE);
                }
            }
        }).show();
    }

    private void takePhoto() {
        if (!filePath.getParentFile().exists())
            filePath.getParentFile().mkdirs();
        Uri mUri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mUri = FileProvider.getUriForFile(this, "com.leave.tools.fileprovider", filePath);
        } else {
            mUri = Uri.fromFile(filePath);
        }
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(intent, CAMERA_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_RESULT_CODE:
                viewModel.upLoadImageFile(filePath.getPath());
                break;

            case SELECTPIC_RESULT_CODE:
                Uri mUri = data.getData();
                String path = FileUtil.getFilePathByUri(this, mUri);
                viewModel.upLoadImageFile(path);
                break;

            default:
                break;
        }
    }


}
